#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/10/7 9:51
# @Author  : leon yan
# @Site    : 
# @File    : qpulsethread.py
# @Software: PyCharm
import datetime
import threading
import time
from datetime import date
from threading import Lock
import Globalist as gl
from lib.qsqledit import NewProductLogDB, ReadTodayDB, UpdateDB
from PyQt5.QtCore import QObject, pyqtSignal


def save2LogData(lst):
    loginUser = gl.get_value("LoginUser")
    if loginUser:
        loginUser = gl.get_value("LoginUser")
    else:
        loginUser = ""
    saveList = [lst[0], lst[1], lst[2], lst[3], lst[4], loginUser]
    NewProductLogDB([saveList])


def update2DbData(dbName, dctUpLst, idList):
    loginUser = gl.get_value("LoginUser")
    if loginUser:
        loginUser = gl.get_value("LoginUser")
    else:
        loginUser = ""
    UpdateDB(dbName, dctUpLst, idList)


class QPollThread(QObject):
    bPulse = pyqtSignal()

    def __init__(self):
        super().__init__()
        # init a thread lock
        self.regs_lock = Lock()
        self.counter = 0

    '''
    '''

    def polling_thread(self):
        # polling loop
        while True:
            self.bPulse.emit()
            time.sleep(0.5)

    def polling_thread2(self):
        # polling loop
        while True:
            self.doSomething()
            time.sleep(1.0)

    def doSomething(self):
        gl.global_var["monitorVar"]["PowerTime"] += 1
        if gl.global_var["statusVar"]["bRunning"]:
            gl.global_var["monitorVar"]["WorkTime"] += 1
        if gl.global_var["statusVar"]["bAlarm"]:
            gl.global_var["monitorVar"]["AlarmTime"] += 1

        aa = gl.global_var["monitorVar"]["TotalPower"]
        bb = gl.global_var["monitorVar"]["TodayStartPower"]
        gl.global_var["monitorVar"]["TodayPower"] = round(aa - bb, 2)
        '''total time'''
        aa1 = gl.global_var["monitorVar"]["WorkTime"] / gl.global_var["monitorVar"]["PowerTime"]
        aa2 = gl.global_var["monitorVar"]["AlarmTime"] / gl.global_var["monitorVar"]["PowerTime"]
        aa3 = 100-aa1-aa2

        gl.global_var["chartMonitor"]["timeMonitor"][0][1] = round(aa1, 1)
        gl.global_var["chartMonitor"]["timeMonitor"][1][1] = round(aa2, 1)
        gl.global_var["chartMonitor"]["timeMonitor"][2][1] = round(aa3, 1)

        currentDate = datetime.datetime.strftime(datetime.datetime.now(), '%Y/%m/%d')
        self.counter += 1
        if self.counter > 5:
            gl.global_config['working']["PowerTime"] = gl.global_var["monitorVar"]["PowerTime"]
            gl.global_config['working']["WorkTime"] = gl.global_var["monitorVar"]["WorkTime"]
            gl.global_config['working']["AlarmTime"] = gl.global_var["monitorVar"]["AlarmTime"]
            gl.global_config.write()

            '''new DB'''
            strWhere = "LogTime like '%" + currentDate + "%'"
            ret = ReadTodayDB("ProductLog", strWhere)
            if not ret:
                lst = [aa, 0.0, 0.0, 0.0, 0.0, "", 0.0, 0.0]
                save2LogData(lst)
            '''update'''
            a1 = gl.global_var["monitorVar"]["TotalPower"]
            updateDict = {}
            if a1 > 0:
                updateDict["TotalPower"] = round(a1, 1)
                updateDict["LogIniPower"] = round(a1, 1)
            a2 = gl.global_var["monitorVar"]["TotalAmount"]
            if a2 > 0:
                updateDict["TotalAmount"] = round(a2, 1)
                updateDict["LogIniAmount"] = round(a2, 1)


            self.counter = 0


if __name__ == '__main__':
    # while True:
    tpj = QPollThread()
    theThread1 = threading.Thread(target=tpj.polling_thread)
    theThread1.daemon = True
    theThread1.start()
    while True:
        pass
